from datetime import date, datetime, timedelta
from dateutil.relativedelta import relativedelta
from flask_restx import fields

class TimeAgo(fields.Raw):
    def format(self, dt):
        now = datetime.now()

        if now - dt < timedelta(seconds = 3): # timedelta()作用：创建时间间隔对象
            return '刚刚'
        diff = relativedelta(now, dt) # relativedelta()作用：计算时间间隔

        if diff.years > 0:
            return '{}年前'.format(diff.years)
        if diff.months > 0:
            return '{}个月前'.format(diff.months)
        if diff.days > 0:
            return '{}天前'.format(diff.days)
        if diff.hours > 0:
            return '{}小时前'.format(diff.hours)
        if diff.minutes > 0:
            return '{}分钟前'.format(diff.minutes)
        
        return '{}秒前'.format(diff.seconds)

class ShortTime(fields.Raw):
    def format(self, dt):
        today = date.today()

        if dt.date() == today:
            return dt.strftime('%H:%M')
        if dt.date() == today - timedelta(days=1):
            return '昨天{}'.format(dt.strftime('%H:%M'))
        elif dt.year == today.year:
            return dt.strftime('%m-%d %H:%M')
        
        return dt.strftime('%Y-%m-%d %H:%M')